package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Email;
import com.acme.bankapp.util.EmailQueue;

import java.io.Closeable;

public class EmailService implements Closeable {
    private EmailQueue emailQueue = new EmailQueue();
    private volatile boolean isClosed;

    public void start() {
        new Thread() {
            @Override
            public void run() {
                while (!isClosed || !emailQueue.isEmpty()) {
                    try {
                        Email email = emailQueue.dequeue();
                        Thread.sleep(1000);  //Emulate LONG SLOW EMAIL sending
                        System.out.println("Notification sent to client " + email.getReceiver());
                    } catch (InterruptedException e) {
                        System.out.println("Interruption call");
                    }
                }
            }
        }.start();
    }

    public boolean sendNotificationEmail(Email email) {
        if (!isClosed) {
            emailQueue.enqueue(email);
            return true;
        } else {
            return false;
        }
    }

    public void close() {
        isClosed = true;
        Thread.currentThread().interrupt();
    }
}
